<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="分类" prop="categoryId">
                <treeselect v-model="queryParams.categoryId" :options="categoryOptions" :show-count="true"
                    placeholder="请选择分类" />
            </el-form-item>
            <el-form-item label="产品名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入产品名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="产品编号" prop="productNumber">
                <el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="产品价格" prop="price">
        <el-input
          v-model="queryParams.price"
          placeholder="请输入价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['product:product:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['product:product:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['product:product:remove']">删除</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出</el-button>
      </el-col> -->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="产品ID" align="center" prop="id" />
            <el-table-column label="分类" align="center" width="200">
                <template slot-scope="scope">
                    <span v-if="scope.row.category">{{ scope.row.category.parentName || ''}} | {{ scope.row.category.name||'' }}</span>
                    <span v-else>{{ scope.row.categoryName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="产品名称" align="center" prop="name" />
            <el-table-column label="产品编号" align="center" prop="productNumber" />
            <el-table-column label="颜色定制" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.isColorCustom === 0">不支持</span>
                    <span v-if="scope.row.isColorCustom === 1">支持</span>
                </template>
            </el-table-column>
            <el-table-column label="颜色定制价格" align="center" prop="colorCustomPrice" />
            <!-- <el-table-column label="门中门" align="center">
        <template slot-scope="scope">
            <span v-if="scope.row.isIndoor===0">不支持</span>
            <span v-if="scope.row.isIndoor===1">支持</span>
        </template>
      </el-table-column> 
      <el-table-column label="门中门价格" align="center" prop="indoorPrice" /> -->
            <el-table-column label="多属性产品" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.type === 0">否</span>
                    <span v-if="scope.row.type === 1">是</span>
                </template>
            </el-table-column>
            <el-table-column label="产品价格" align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.price }}元/{{ scope.row.unit }}</span>
                </template>
            </el-table-column>
            <el-table-column label="产品头图" align="center">
                <template slot-scope="scope">
                    <image-preview :src="scope.row.imageUrl" width="30px" height="30px"></image-preview>
                </template>
            </el-table-column>
            <el-table-column label="排序" align="center" prop="sortNo" />
            <el-table-column label="产品描述" align="center" prop="description" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['product:product:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['product:product:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改产品对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-form-item label="产品分类" prop="categoryId">
                    <treeselect v-model="form.categoryId" :options="categoryOptions" :show-count="true"
                        placeholder="请选择分类" />
                </el-form-item>
                <el-form-item label="产品名称" prop="name">
                    <el-col :span="12">
                        <el-input v-model="form.name" placeholder="请输入产品名称" />
                    </el-col>
                </el-form-item>
                <el-form-item label="产品编号" prop="productNumber">
                    <el-col :span="12">
                        <el-input v-model="form.productNumber" placeholder="请输入产品编号" />
                    </el-col>
                </el-form-item>
                <el-form-item label="排序" prop="sortNo">
                    <el-col :span="12">
                        <el-input v-model="form.sortNo" placeholder="请输入产品序号" />
                    </el-col>
                </el-form-item>
                <el-form-item label="颜色定制" prop="isColorCustom">
                    <el-col :span="6">
                        <el-radio-group v-model="form.isColorCustom">
                            <el-radio :label="0">不支持</el-radio>
                            <el-radio :label="1">支持</el-radio>
                        </el-radio-group>
                    </el-col>
                </el-form-item>
                <el-form-item v-if="form.isColorCustom === 1" label="颜色定制价格" prop="colorCustomPrice">
                    <el-col :span="6">
                        <el-input-number v-model="form.colorCustomPrice" controls-position="right" :min="0"
                            :precision="2" />
                    </el-col>
                </el-form-item>
                <!-- <el-form-item label="门中门" prop="isIndoor" >
            <el-col :span="6">
                <el-radio-group v-model="form.isIndoor">
                    <el-radio :label="0">不支持</el-radio>
                    <el-radio :label="1">支持</el-radio>
                </el-radio-group>
            </el-col>
        </el-form-item>
        <el-form-item v-if="form.isIndoor" label="门中门价格" prop="indoorPrice" >
            <el-col :span="6">
                <el-input-number 
                    v-model="form.indoorPrice"
                    controls-position="right" 
                    :min="0" 
                    :precision="2"  />
            </el-col>
        </el-form-item> -->
                <el-form-item label="产品类型" prop="type">
                    <el-radio-group v-model="form.type" @change="prodTypeChangeHandler">
                        <el-radio :label="0">单属性</el-radio>
                        <el-radio :label="1">多属性</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- <el-form-item v-if="form.type==0" label="产品属性" prop="attrIds">
            <treeselect v-model="form.attrIds" :options="attrOptions" :multiple="true" :show-count="true" placeholder="请选择分类" />
        </el-form-item> -->
                <template v-if="form.type === 0">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="产品价格" prop="price">
                                <el-input-number v-model="form.price" controls-position="right" placeholder="请输入价格"
                                    :min="0" :precision="2" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="" prop="unit">
                                <el-select v-model="form.unit" placeholder="请选择价格单位">
                                    <el-option v-for="item in unitOptions" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <el-form-item label="产品头图" prop="imageUrl">
                    <el-col :span="12">
                        <image-upload v-model="form.imageUrl" :fileSize="2"></image-upload>
                    </el-col>
                </el-form-item>
                <!-- 树形属性选择 -->
                <template v-if="form.type === 1">
                    <el-form-item label="开门方式">
                        <treeselect v-model="openTypeAttrSelected" :multiple="true" :options="openTypeOptions"
                            :flat="true" value-format="object" value-key="id" placeholder="选择开门方式"
                            @select="handleAttributeSelect" @deselect="handleAttributeDeselect(1)" clearable>
                        </treeselect>
                    </el-form-item>
                    <el-form-item label="颜色">
                        <treeselect v-model="colorAttrSelected" :multiple="true" :options="colorOptions" :flat="true"
                            value-format="object" value-key="id" placeholder="选择颜色" @select="handleAttributeSelect"
                            @deselect="handleAttributeDeselect(2)" clearable>
                        </treeselect>
                    </el-form-item>
                    <!-- <el-form-item label="小门单套价格" prop="smallDoorUnitPrice">
                        <el-input-number v-model="form.smallDoorUnitPrice" :min="0" :precision="2"
                            placeholder="请输入小门单套价格" />
                    </el-form-item>
                    <el-form-item label="小门单套无忧包价格" prop="smallDoorUnitServicePrice">
                        <el-input-number v-model="form.smallDoorUnitServicePrice" :min="0" :precision="2"
                            placeholder="请输入小门单套无忧包价格" />
                    </el-form-item> -->
                    <el-form-item label="产品SKU列表">
                        <el-button @click="uploadDialogVisible = true">上传图片</el-button>
                        <el-table :data="form.skus" :border="true">
                            <el-table-column prop="attributes[0].label" label="开门方式" width="100" />
                            <el-table-column prop="attributes[1].label" label="颜色" width="100" />
                            <el-table-column label="价格">
                                <template #default="{ row }">
                                    <el-input-number @blur="priceChangeHandler(row)" v-model="row.price" :min="0"
                                        :precision="2" controls-position="right" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位">
                                <template #default="{ row }">
                                    <el-select v-model="row.unit" placeholder="请选择单位">
                                        <el-option v-for="item in unitOptions" :key="item.value" :label="item.label"
                                            :value="item.value">
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="主图">
                                <template #default="{ row }">
                                    <el-image style="width: 50px; height: 50px" :src="row.imageUrl" fit="fill"
                                        :preview-src-list="[row.imageUrl]"></el-image>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </template>
                <el-form-item label="产品描述" prop="description">
                    <el-col :span="12">
                        <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
                    </el-col>
                </el-form-item>
                <el-form-item label="产品详情">
                    <editor v-model="form.content" :min-height="192" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>

        </el-dialog>

        <el-dialog title="上传产品图片" :visible.sync="uploadDialogVisible" width="800px" append-to-body>
            <div>图片命名方式为：开门方式-颜色.jpg</div>
            <!-- 图片上传 -->
            <prod-image-upload v-model="imageList" :fileType="uploadFileType" :limit="9" :fileSize="2" />
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleUploadSuccess">确 定</el-button>
                <el-button @click="handlerUploadCancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct } from "@/api/product/product";
import { categoryTree } from '@/api/product/category';
import { queryAttributeTree } from '@/api/product/attribute';
import { queryConfigTree } from '@/api/product/config';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ProdImageUpload from '@/components/ProdImageUpload/index';

export default {
    name: "Product",
    components: {
        Treeselect,
        ProdImageUpload
    },
    data () {
        return {
            categoryOptions: undefined,
            openTypeOptions: undefined,
            openTypeAttrSelected: [],
            colorOptions: undefined,
            colorAttrSelected: [],
            modelOptions: undefined,
            unitOptions: [
                {
                    label: '平方米',
                    value: '平方米'
                }, {
                    label: '套',
                    value: '套'
                }
            ],
            selectedAttributes: {},
            imageList: [],
            uploadDialogVisible: false,
            uploadFileType: ['png', 'jpg', 'jpeg'],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 产品表格数据
            productList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                categoryId: null,
                name: null,
                productNumber: null,
                price: null,
                status: null,
                description: null,
            },
            // 表单参数
            form: {
            },
            // 表单校验
            rules: {
                categoryId: [
                    { required: true, message: "分类不能为空", trigger: "blur" }
                ],
                name: [
                    { required: true, message: "产品名称不能为空", trigger: "blur" }
                ],
                attrIds: [
                    { required: true, message: "属性不能为空", trigger: 'blur' }
                ],
                type: [
                    { required: true, message: "类型不能为空", trigger: 'blur' }
                ],
                isColorCustom: [
                    { required: true, message: "请选择是否支持颜色定制", trigger: 'blur' }
                ],
                // isIndoor:[
                //     {required:true,message:"请选择是否支持门中门",trigger:'blur'}
                // ],
            }
        };
    },
    created () {
        this.getList();
        this.getCategoryTree();
        this.getAttrTree();
        // this.getConfigTree();
    },
    methods: {
        prodTypeChangeHandler (value) {
            console.log('prodTypeChangeHandler', value);
            if (value === 0) {//单属性,清空多属性列表
                this.openTypeAttrSelected = []
                this.colorAttrSelected = []
                this.form.skus = []
            }
        },
        getCategoryTree () {
            categoryTree().then(response => {
                this.categoryOptions = response.data;
            })
        },
        getAttrTree () {
            queryAttributeTree().then(response => {
                console.log('attrOptions', response.data);
                if (response.data && response.data.length > 0) {
                    response.data.forEach(it => {
                        if (it.id === 1) {
                            this.openTypeOptions = it.children;
                        } else if (it.id === 2) {
                            this.colorOptions = it.children;
                        }
                    })
                }
                console.log(this.openTypeOptions, this.colorOptions)
            })
        },
        // getConfigTree(){
        //     queryConfigTree().then(response=>{
        //         this.configOptions=response.data;
        //     })
        // },
        /** 多属性处理start*/
        // 处理属性选择
        handleAttributeSelect (selectedNode, instanceId) {
            this.$nextTick(() => {
                this.generateSkus()
            })
        },
        // 处理取消选择属性
        handleAttributeDeselect (deselectedNode, instanceId, groupId) {
            // 更新选中状态
            this.$nextTick(() => {
                if (groupId === 1) {
                    this.openTypeAttrSelected = this.openTypeAttrSelected?.filter(attr => attr.id !== deselectedNode.id) || [];
                } else if (groupId === 2) {
                    this.colorAttrSelected = this.colorAttrSelected?.filter(attr => attr.id !== deselectedNode.id) || [];

                }
                // 重新生成SKU
                this.generateSkus()
            })
        },

        // 生成SKU逻辑优化
        generateSkus () {
            let oldSkus = []
            if (this.form.skus) {
                oldSkus = [...this.form.skus];
            }

            const selectedValues = [this.openTypeAttrSelected, this.colorAttrSelected];
            if (selectedValues.length === 0) {
                this.form.skus = []
                return
            }
            console.log("selectedValues", selectedValues);
            // 生成笛卡尔积
            const combinations = this.cartesianProduct(selectedValues)
            this.form.skus = combinations.map(combo => {
                let sku = this.generateSkuCode(combo);
                const oldObj = oldSkus.find(s => s.sku === sku);
                if (oldObj) {
                    return oldObj;
                } else {
                    return {
                        sku: sku,
                        name: this.generateSkuName(combo),
                        attributes: combo,
                        unit: '平方米',
                        price: 0
                    }
                }
            })
            this.form.skus.sort((a, b) => a.sku.localeCompare(b.sku));
        },

        cartesianProduct (arr) {
            return arr.reduce((a, b) =>
                a.flatMap(x =>
                    b.map(y => [...x, y])
                ), [[]]
            );
        },
        priceChangeHandler (row) {
            if (row) {
                this.form.skus.forEach(it => {
                    if (it.attributes[0].label === row.attributes[0].label) {
                        it.price = row.price;
                    }
                })
            }
        },
        // 生成SKU编码（带分组信息）
        generateSkuCode (attributes) {
            return `${attributes.map(a => a.id).join('-')}`
        },
        generateSkuName (attributes) {
            return `${attributes.map(a => a.label).join('-')}`
        },
        /**多属性处理end */
        /** 图片上传处理 start */
        // 图片上传成功处理
        handleUploadSuccess () {
            console.log('imagelist', this.imageList);
            // 从文件名解析SKU（示例：PROD001-RED-S.jpg）
            this.imageList.forEach(image => {
                const sku = image.orginFileName.split('.')[0].toUpperCase();
                this.form.skus.forEach((item, index) => {
                    if (item.name === sku) {
                        this.$set(this.form.skus[index], 'imageUrl', image.url);
                    }
                })
                console.log('skus', this.form.skus);
            });
            this.uploadDialogVisible = false;
        },
        handlerUploadCancel () {
            this.imageList = [];
            this.uploadDialogVisible = false;
        },

        // 上传前校验
        beforeUpload (file) {
            const isValid = /^[A-Z0-9-]+\.(jpg|png)$/i.test(file.name);
            if (!isValid) {
                this.$message.error('文件名必须为SKU格式（例如：开门方式-颜色.jpg）');
            }
            return isValid;
        },
        /** 图片上传处理 end */

        /** 查询产品列表 */
        getList () {
            this.loading = true;
            listProduct(this.queryParams).then(response => {
                this.productList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.reset();
            this.open = false;
        },
        // 表单重置
        reset () {
            this.form = {
                id: null,
                categoryId: null,
                name: null,
                productNumber: null,
                sortNo: 0,
                type: 0,
                isColorCustom: 0,
                colorCustomPrice: 8000,
                price: null,
                unit: '平方米',
                smallDoorUnitPrice: null,
                smallDoorUnitServicePrice: null,
                imageUrl: null,
                status: null,
                description: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                skus: null,
                attributes: null
            };
            this.openTypeAttrSelected = []
            this.colorAttrSelected = []
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.open = true;
            this.title = "添加产品";
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const id = row.id || this.ids
            getProduct(id).then(response => {
                this.form = response.data;
                if (this.form.type === 1) {
                    response.data.attributes.forEach(it => {
                        if (it.id === 1) {
                            this.openTypeAttrSelected = it.children;
                        } else if (it.id === 2) {
                            this.colorAttrSelected = it.children;
                        }
                    })
                }
                if (this.form.skus) {
                    this.form.skus.sort((a, b) => a.sku.localeCompare(b.sku));
                }
                this.open = true;
                this.title = "修改产品";
            });
        },
        /** 提交按钮 */
        submitForm () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.type === 1) {
                        const attrs = [{
                            id: 1,
                            label: '开门方式',
                            children: this.openTypeAttrSelected
                        }, {
                            id: 2,
                            label: '颜色',
                            children: this.colorAttrSelected
                        }]
                        this.form.attributes = attrs;
                    }
                    if (this.form.id != null) {
                        updateProduct(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addProduct(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除产品编号为"' + ids + '"的数据项？').then(function () {
                return delProduct(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport () {
            this.download('product/product/export', {
                ...this.queryParams
            }, `product_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>
<style>
/* 调整树形选择器样式与Element UI一致 */
.vue-treeselect {
    width: 320px;
}

.vue-treeselect__control {
    border-radius: 4px;
    border-color: #dcdfe6;
}

.vue-treeselect__menu {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}
</style>